package cn.edu.gzist.chapter08.rabbitmqclient;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ProducerTopic {
    //交换机名称
    static final String TOPIC_EXCHANGE="topic_exchange";
    //队列名称
    static final String TOPIC_QUEUE_1="topic_queue_1";
    //队列名称
    static final String TOPIC_QUEUE_2="topic_queue_2";

    public static void main(String[] args) throws Exception {
        //创建连接
        /** 1.创建新的连接 */
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        //创建channel
        Channel channel = connection.createChannel();

        //声明交换机
        /**
         * 参数1：交换机名称
         * 参数2：交换机类型fanout，topic，direct，headers
         */
        channel.exchangeDeclare(TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC);

        //声明队列
        /**
         * 参数一：队列名称
         * 参数二：是否定义持久化队列
         * 参数三：是否独占本次连接
         * 参数四：会否在不使用的时候自动删除队列
         * 参数五：队列其他参数
         */
        channel.queueDeclare(TOPIC_QUEUE_1,true,false,false,null);
        channel.queueDeclare(TOPIC_QUEUE_2,true,false,false,null);


        //队列绑定交换机（#代表可以多个字符，*代表只能一个字符）——如果已存在队列并且绑定好了，这段也不需要
        channel.queueBind(TOPIC_QUEUE_1,TOPIC_EXCHANGE,"item.#");
        channel.queueBind(TOPIC_QUEUE_2,TOPIC_EXCHANGE,"*.delete");

        //4.发送消息
        String msg = "新增商品，Topic模式：routingkey为item.insert";
        channel.basicPublish(TOPIC_EXCHANGE,"item.insert",null,msg.getBytes());
        System.out.println("已发送消息："+msg);

        //4.发送消息
        msg = "修改商品，Topic模式：routingkey为item.update";
        channel.basicPublish(TOPIC_EXCHANGE,"item.update",null,msg.getBytes());
        System.out.println("已发送消息："+msg);

        //4.发送消息
        msg = "删除商品，Topic模式：routingkey为item.delete";
        channel.basicPublish(TOPIC_EXCHANGE,"item.delete",null,msg.getBytes());
        System.out.println("已发送消息："+msg);

        //关闭连接
        channel.close();
        connection.close();
    }
}
